const crypto = require('crypto')

const helper = {
  algorithm: 'aes-256-ctr',
  password: process.env.AES_SECRET_KEY,
  // 加密
  // deprecated
  encrypt(buffer) {
    const cipher = crypto.createCipher(this.algorithm, this.password)
    return Buffer.concat([cipher.update(buffer), cipher.final()])
  },
  /**
   * aes加密
   * @param data 待加密内容
   * @param key 必须为32位私钥
   * @return {string}
   */
  encryption(data, key, iv = '') {
    let cipherChunks = []
    const cipher = crypto.createCipheriv('aes-256-ecb', key, iv)

    cipher.setAutoPadding(true)
    cipherChunks.push(cipher.update(data, 'utf8', 'base64'))
    cipherChunks.push(cipher.final('base64'))

    return cipherChunks.join('')
  },
  // 解密
  // deprecated
  decrypt(buffer) {
    const decipher = crypto.createDecipher(this.algorithm, this.password)
    return Buffer.concat([decipher.update(buffer) , decipher.final()])
  },
  decryption(data, key, iv = '') {
    let cipherChunks = []

    const decipher = crypto.createDecipheriv('aes-256-ecb', key, iv)
    decipher.setAutoPadding(true)
    cipherChunks.push(decipher.update(data, 'base64', 'utf8'))
    cipherChunks.push(decipher.final('utf8'))

    return cipherChunks.join('')
  }
}

module.exports = helper